package com.hy.admin.controller.pages;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.hy.admin.helper.response.NewsResponse;
import com.hy.admin.security.utils.MyHttpclientUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.hy.admin.domain.dto.AdminWebUserDto;
import com.hy.admin.entity.FreeCourseTypeEntity;
import com.hy.admin.entity.MemberEntity;
import com.hy.admin.entity.MemberQuestionEntity;
import com.hy.admin.entity.NewsEntity;
import com.hy.admin.helper.request.TeacherRequest;
import com.hy.admin.helper.response.CourseResponse;
import com.hy.admin.service.CourseSeriesService;
import com.hy.admin.service.CourseService;
import com.hy.admin.service.NewsService;
import com.hy.admin.service.QuestionService;
import com.hy.admin.service.TeacherService;
import com.hy.core.response.ServicesResult;
import com.hy.utils.HyRequestHandler;

@Controller
@RequestMapping("/page/admin")
public class PageControllerAdmin extends PageControllerBase{
	
	@Value("${admin.username}")
	private String adminUserName;
	
	@Value("${admin.passwd}")
	private String adminPasswd;
	
	@Value("${security.admin.Authorization}")
	private String headerAuthorization;

	@Autowired
	private CourseService courseServiceImpl;
	@Autowired
	private TeacherService teacherServiceImpl;
	@Autowired
    private CourseSeriesService courseSeriesServiceImpl;
	@Autowired
    private QuestionService questionService;
	@Autowired
	private NewsService newsServiceImpl;
	
	@RequestMapping(value={"", "/", "/login" }, method=RequestMethod.GET)
	public String toLogin(Model model) {
//		if(isLogin(ROLE_ADMIN)) return "redirect:/page/admin/adminMain";
		
		saveDefaultAttributes2Model(model);
		
		return makeViewName("login");
	}
	
	@ResponseBody
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public ServicesResult<Object> authen(String username, String password) {
		ServicesResult<Object> result = new ServicesResult<Object>();
		AdminWebUserDto adminWebUserDto=null;
		if(StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			result.setResult(adminWebUserDto);
		}
		else {
			boolean flag = this.adminUserName.equals(username.trim()) && this.adminPasswd.equals(password.trim());
			if(flag) {
				try {
					Map<String, String> param = new HashMap<>();  
					param.put("grant_type", "password");
					param.put("username", username);
					param.put("password", password);
					ObjectMapper objectMapper=new ObjectMapper();
					String realPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
					String resp = MyHttpclientUtils.doPost(realPath+"/oauth/token",headerAuthorization, param);
					if (StringUtils.isNotBlank(resp)) {
						adminWebUserDto = objectMapper.readValue(resp, AdminWebUserDto.class);
						markedLogin(username.trim(), ROLE_ADMIN);
					}
					
				} catch (Exception e) {
					flag=false;
					e.printStackTrace();
				}
			}
			
			result.setResult(adminWebUserDto);
		}
		return result;
	}

	@RequestMapping(value="/teachers", method=RequestMethod.GET)
	public String toTeachers(Model model) {
//		if(!isLogin(ROLE_ADMIN)) return "redirect:/page/admin/login";
		
		saveDefaultAttributes2Model(model);
		
		Integer total = teacherServiceImpl.countByType();
		model.addAttribute("total", total);
		
		final int pageSize = 10;
		int totalPages = total / pageSize;
		if(total % pageSize > 0) ++totalPages;
		model.addAttribute("totalPages", totalPages);
		
		TeacherRequest teacherRequest = new TeacherRequest();
		teacherRequest.setPageNum(1);
		teacherRequest.setPageSize(10);
		ServicesResult<List<MemberEntity>> servicesResult = teacherServiceImpl.listByType(teacherRequest);
		List<MemberEntity> teachers = servicesResult.getResult();
		model.addAttribute("teachers", teachers);
		
		return makeViewName("teachers");
	}
	
	@RequestMapping(value="/teacher/courses", method=RequestMethod.GET)
	public String toTeacherCoures(Model model, Long teacherId) {
//		if(!isLogin(ROLE_ADMIN)) return "redirect:/page/admin/login";
		
		saveDefaultAttributes2Model(model);
		
		if(teacherId != null) {
			MemberEntity teacher = teacherServiceImpl.selectById(teacherId);
			model.addAttribute("teacher", teacher);
			if(teacher != null) {
				int total = courseServiceImpl.countByMemberId(teacherId);
				model.addAttribute("total", total);
				
				final int pageSize = 10;
				int totalPages = total / pageSize;
				if(total % pageSize > 0) ++totalPages;
				model.addAttribute("totalPages", totalPages);
				
				if(total > 0) {
					ServicesResult<List<CourseResponse>> servicesResult2 = courseServiceImpl.listByMemberId(teacherId, 1, pageSize);
					List<CourseResponse> courses = servicesResult2.getResult();
					model.addAttribute("courses", courses);
				}
				else {
					model.addAttribute("courses", null);
				}
			}
		}
		
		return makeViewName("courses");
	}
	
	@RequestMapping(value="/courseEdit", method=RequestMethod.GET)
	public String toCourseEdit(Model model, Long memberId, Long courseId) {
//		if(!isLogin(ROLE_ADMIN)) return "redirect:/page/admin/login";
		
		saveDefaultAttributes2Model(model);
		
		if(memberId != null) {
			MemberEntity teacher = teacherServiceImpl.selectById(memberId);
			model.addAttribute("teacher", teacher);
		}
		
		if(courseId != null) {
			ServicesResult<CourseResponse> result = courseServiceImpl.detail(courseId, memberId);
			if(result != null && result.getResult() != null) {
				CourseResponse course = result.getResult();
				model.addAttribute("course", course);
				
				if(course.getSeriesId() == null) {
					course.setName("无");
				}
			}
			
			FreeCourseTypeEntity freeType = courseServiceImpl.getCourseFreeType(courseId).getResult();
			if(freeType == null) {
				model.addAttribute("freeType", -1);
			}
			else {
				model.addAttribute("freeType", freeType.getCourseType());
			}
		}
		
		return makeViewName("courseEditAdmin");
	}
	
	@RequestMapping(value="/teacher/questions", method=RequestMethod.GET)
	public String toTeacherQuestions(Model model, Long teacherId) {
//		if(!isLogin(ROLE_ADMIN)) return "redirect:/page/admin/login";
		
		saveDefaultAttributes2Model(model);
		
		if(teacherId != null) {
			MemberEntity teacher = teacherServiceImpl.selectById(teacherId);
			model.addAttribute("teacher", teacher);
			if(teacher != null) {
				PageInfo<MemberQuestionEntity> page = questionService.listByTeacherId(teacherId, 1, 10);
				model.addAttribute("page", page);
				
			}
		}
		
		return makeViewName("teacherQuestionsAdmin");
	}
	
	@RequestMapping(value="/news/add", method=RequestMethod.GET)
	public String toNewsAdd(Model model) {
//		if(!isLogin(ROLE_ADMIN)) return "redirect:/page/admin/login";
		
		saveDefaultAttributes2Model(model);
		
		return makeViewName("newsAddAdmin");
	}

	@RequestMapping(value="/news/edit", method=RequestMethod.GET)
	public String toNewsEdit(Model model, Long newsId) {
//		if(!isLogin(ROLE_ADMIN)) return "redirect:/page/admin/login";

		saveDefaultAttributes2Model(model);

		if(newsId != null){
			ServicesResult<NewsResponse> result = newsServiceImpl.detail(newsId);
			model.addAttribute("news", result.getResult());
		}
		return makeViewName("newsEditAdmin");
	}

	@RequestMapping(value="/news", method=RequestMethod.GET)
	public String toNewsList(Model model, String keyWord, Integer pageNum, Integer pageSize) {
//		if(!isLogin(ROLE_ADMIN)) return "redirect:/page/admin/login";
		
		saveDefaultAttributes2Model(model);
		
		PageInfo<NewsEntity> pageInfo = newsServiceImpl.listByKeyWord(keyWord, pageNum, pageSize);
		model.addAttribute("pageInfo", pageInfo);
		
		if(StringUtils.isBlank(keyWord)) keyWord = "";
		model.addAttribute("keyWord", keyWord);
		
		return makeViewName("newsAdmin");
	}	
	
	@Override
	protected String getViewPrefix() {
		return "admin/";
	}
	
	@RequestMapping(value="adminMain", method=RequestMethod.GET)
	public String adminMain(Model model) {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		if (!SecurityContextHolder.getContext().getAuthentication().getName().
				  equals("anonymousUser")) {
				  System.out.println("LOGGED IN");
				  System.out.println();
				  } else {
				  System.out.println("NOT LOGGED IN");
				}
		
//		if(!isLogin(ROLE_ADMIN)) return "redirect:/page/admin/login";
		
		saveDefaultAttributes2Model(model);
		
		return makeViewName("index");
	}
}
